In this lab session, we will quickly give ChatGPT a try and then dive into network analysis in R using the igraph package.

We’ve already discussed ChatGPT in the lecture So let’s check it out quickly.

To use it during the free research beta, you can sign up with OpenAI.

What’s cool is that we can also ask it to write R code for us.

While this is a and can help us if we get stuck or need to get started, it is important to note that these types of language models cannot actually reason or understand things independently, they only learn relationships between words, so be careful!

Network basics in igraph

The igraph package provides a comprehensive suite of functions for creating and analyzing complex network data. We will start out by covering the basics of using igraph to create and visualize networks, compute important network statistics, and manipulate and analyze network data.

First, let’s start by installing and loading the igraph package in R:

install.packages("igraph")

In addition to igraph, we will also load the dplyrpackage.1

library(igraph)
## 
## Attaching package: 'igraph'
## The following objects are masked from 'package:stats':
## 
##     decompose, spectrum
## The following object is masked from 'package:base':
## 
##     union
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:igraph':
## 
##     as_data_frame, groups, union
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union

Our first network2

Let’s consider a network this network of friends.

Next, we can start translating this into code. We will start with a data.frame that has two columns to represent the friends.

personA <- c("Bob", "Bob", "Aaron", "Aaron", "Mark", "Mark")
personB <- c("Peter", "Jill", "Jill", "Peter", "Jill", "Peter")

edges <- data.frame(
  personA,
  personB
)

Let’s take a look at the data.frame we created:

View(edges)

We can use this list of edges to create a network with the graph_from_data_frame function:

g <- graph_from_data_frame(edges, directed=FALSE)

Now that we have a network, we can use the plot function to visualize it. By default, the plot function will use a force-directed layout to arrange the nodes in the network, resulting in a visually pleasing and easy to interpret plot:

plot(g)

Now, let’s consider a directed graph. These are the texts the friends sent over the weekend:

A directed edge means that someone reached out to someone over the weekend. Let’s start importing this into R:

sender <- c('Bob',  'Peter', 'Peter', 'Jill', 'Jill', 'Aaron', 'Mark')
receiver <- c('Peter', 'Bob', 'Mark', 'Mark', 'Bob', 'Mark', 'Jill')

messages <- data.frame(sender, receiver)

gm <- graph_from_data_frame(messages)

plot(gm)

Alternatively, we can also create a network from an adjacency matrix, which is a matrix that encodes the connections between nodes in a network. To create our network from an adjacency matrix in igraph, you can use the following code:

# Create an adjacency matrix
adjmat <- matrix(
  c(0, 1, 0, 0, 0,
    1, 0, 0, 0, 1,
    1, 0, 0, 0, 1,
    0, 0, 0, 0, 1,
    0, 0, 1, 0, 0),
  nrow = 5,
  ncol = 5,
  dimnames = list(c('Bob', 'Peter', 'Jill', 'Aaron', 'Mark'), # rows
                  c('Bob', 'Peter', 'Jill', 'Aaron', 'Mark')), # columns
  byrow = TRUE
)

# Convert the adjacency matrix to an igraph object
gm_adj <- graph_from_adjacency_matrix(adjmat,
                                  mode = 'directed')

# Plot the network
plot(gm_adj)

This code creates an adjacency matrix, which encodes the connections between nodes in the network. The graph_from_adjacency_matrix function is then used to convert the adjacency matrix into an igraph object. Note that adjacency matrices are actually not that useful for humans (they are for machines, though) and we can get the adjacency matrix of an existing graph using as_adjacency_matrix().

Network measures

In addition to visualizing networks, igraph also provides a wide range of functions for computing important network statistics. For example, we can use the degree function to compute the degree centrality of each node in the network, which represents the number of connections each node has:

degree(gm)
##   Bob Peter  Jill Aaron  Mark 
##     3     3     3     1     4

By default, degree gives us the number of all edges going in and out. We can also get the in- and outdegree, respectively:

degree(gm, mode = 'in')
##   Bob Peter  Jill Aaron  Mark 
##     2     1     1     0     3
degree(gm, mode = 'out')
##   Bob Peter  Jill Aaron  Mark 
##     1     2     2     1     1

We can also use the betweenness function to compute the betweenness centrality, which measures the importance of a node in terms of the number of shortest paths that pass through it:

betweenness(gm)
##   Bob Peter  Jill Aaron  Mark 
##     3     2     4     0     5

Note that we do not get even numbers here because the way betweenness is calculated. The number of the shortest paths that pass through a node is divided by the number of all paths that pass through it.

Finally, we can calculate the closeness centrality, a measure for how many steps are required to access every other node from a given node, using the closeness function:

closeness(gm)
##       Bob     Peter      Jill     Aaron      Mark 
## 0.1666667 0.2500000 0.2500000 0.1000000 0.1666667

Note that the closeness values by default represent the average length of the shortest paths that go through a node. To get the full number of edges, we need to run:

1/closeness(gm)
##   Bob Peter  Jill Aaron  Mark 
##     6     4     4    10     6

Next, let’s consider some network characteristics. To get the number of nodes and eges in a network, we can use the V and E functions3, respectively:

length(V(gm))
## [1] 5
length(E(gm))
## [1] 7

To calculate the density of the network (actual edges over all possible edges between nodes):

edge_density(gm)
## [1] 0.35

Manipulating the network

Finally, igraph also provides a number of functions for manipulating and analyzing network data. For example, we can use the subgraph function to extract a subnetwork from the original network, or the add_vertices, delete_vertices, add_edges, delete_edges function to add / remove nodes / edges from the network:

First, let’s extract the relationship between Jill, Mark and Aaron from the graph:

subg <- subgraph(gm, v = c('Jill', 'Mark', 'Aaron'))
plot(subg)

Now let’s take a deeper look at Mark specifically and find their alters:

mark_ego_size <- ego_size(gm, nodes='Mark') # call the ego_size function to get the number of edges connecting

plot(make_ego_graph(gm, nodes='Mark')[[1]]) # call the make_ego_graph_function to extract mark and alters from the graph

To add / remove, use:

gm <- delete_vertices(g, v = c("Mark"))
plot(gm)

gm <- gm %>%
    add_vertices(nv = 1, attr=list('name'= c('Mark'))) %>% # add mark
    add_edges(c('Mark', 'Jill')) # add edges to the graph

plot(gm)

Visualization

Because are graphs are not that nice looking, we will now explore some additional plotting options provided by igraph4

We can manipulate the nodes in our plot by adding the vertex.size and vertex.color:

plot(gm, vertex.size=30, vertex.color="tomato", vertex.frame.color = NA)

Similarly, we can also adjust the labels (names) of the nodes:

plot(gm, vertex.size=30, vertex.color="tomato", vertex.frame.color = NA,
     vertex.label.cex = .7, vertex.label.color = "black")

And we can get wavy with our edges:

plot(gm, vertex.size=30, vertex.color="tomato", vertex.frame.color = NA,
     vertex.label.cex = .7, vertex.label.color = "black",
     edge.curved = 0.5)

And also really wavy:

plot(gm, vertex.size=30, vertex.color="tomato", vertex.frame.color = NA,
     vertex.label.cex = .7, vertex.label.color = "black",
     edge.curved = 2)

If we want our graph to be a bit more interactive, we can also use another plotting method by using the tkplot function…

tkplot(gm, vertex.size=30, vertex.color="tomato", vertex.frame.color = NA,
     vertex.label.cex = .7, vertex.label.color = "black",
     edge.curved = 0.5)
## [1] 1

…and even go 3D using rglplot(). However, this requires an additional package and performance might differ depending on your setup.

rglplot(gm, vertex.size=30, vertex.color="tomato", vertex.frame.color = NA,
     vertex.label.cex = .7, vertex.label.color = "black",
     edge.curved = 0.5)

German MPs on Twitter5

To test our newly learned skills and add some more, we will now analyze the Twitter friendships (following) of German MPs from the last Bundestag.

We’ll start from two dataset that have been pre-processed (see https://datascience.blog.wzb.eu/2019/07/11/a-twitter-network-of-members-of-the-19th-german-bundestag-part-ii/).

library(tidyr)
## 
## Attaching package: 'tidyr'
## The following object is masked from 'package:igraph':
## 
##     crossing
# read in the datasets and remove the X columnd automatically added by the read.csv function
mp_edges <- read.csv('./mp_edges.csv', as.is=TRUE) %>%
  select(-X)

mp_info <-  read.csv('./mp_info.csv', as.is=TRUE) %>%
  select(-X)

Let’s take a quick look at the data.

head(mp_info)
##   twitter_name     party personal.first_name personal.last_name
## 1         <NA>       FDP           Alexander    Graf Lambsdorff
## 2 martinschulz       SPD              Martin             Schulz
## 3         <NA>       FDP             Michael            Theurer
## 4  fabiodemasi DIE LINKE               Fabio            De Masi
## 5         <NA>       SPD               Sarah          Ryglewski
## 6        anked DIE LINKE                Anke     Domscheit-Berg
head(mp_edges)
##   from_account     to_account from_party   to_party
## 1 martinschulz katarinabarley        SPD        SPD
## 2 martinschulz        oezoguz        SPD        SPD
## 3 martinschulz          kahrs        SPD        SPD
## 4 martinschulz   schneidercar        SPD        SPD
## 5 martinschulz  sigmargabriel        SPD        SPD
## 6 martinschulz      fbrantner        SPD DIE GRÜNEN

We can see that we have one dataset containing information on MPs Names, Twitter usernames and their parties, and, just as before, we have a from and a to list representing follows on Twitter.

We can take a first descriptive look:

# edges per party
mp_edges %>%
    group_by(from_party) %>%
    count()
## # A tibble: 8 × 2
## # Groups:   from_party [8]
##   from_party     n
##   <chr>      <int>
## 1 AfD          404
## 2 CDU         1301
## 3 CSU          248
## 4 DIE GRÜNEN  1735
## 5 DIE LINKE    870
## 6 FDP         1165
## 7 Parteilos     21
## 8 SPD         2819
# mps per party
mp_edges %>%
    distinct(from_account, from_party) %>%
    group_by(from_party) %>%
    count()
## # A tibble: 8 × 2
## # Groups:   from_party [8]
##   from_party     n
##   <chr>      <int>
## 1 AfD           43
## 2 CDU           63
## 3 CSU           15
## 4 DIE GRÜNEN    54
## 5 DIE LINKE     45
## 6 FDP           44
## 7 Parteilos      2
## 8 SPD           90

Now we can get started. Let’s create our graph using igraph. We’ll supply the edge list and some additional information using the vertices argument.

# get party information
party_information <- unique(mp_info)
party_information <- party_information %>%
    drop_na()

# remove unconnected mps
accounts_connected <- unique(c(mp_edges$from_account, mp_edges$to_account))

party_information <- party_information %>%
    filter(twitter_name %in% accounts_connected)

mp_edges <- mp_edges %>%
  filter(from_account %in% accounts_connected) %>%
  filter(to_account %in% accounts_connected)

# create grpahs
mpg <- graph_from_data_frame(mp_edges,
                             vertices = party_information,
                             directed=TRUE)

Let’s try and plot this.

plot(mpg)

Well, that doesn’t tell us much. So, let’s try and find out some of the properties of the network first.

How big is our network?

# number of mps
length(V(mpg))
## [1] 361
# number of follows in the network
length(E(mpg))
## [1] 8563

How dense is our network? → how well connected are MPs overall on Twitter?

You can think about it like this: How far are we from a world where every MP follows every MP (\(density = 1\)).

graph.density(mpg)
## [1] 0.0658895

Centrality

Which MPs follows the most MPs? Who has the most MP followers?

mp_centrality <- degree(mpg)

mp_centrality <- data.frame(mp_name = names(mp_centrality), degree=mp_centrality)

mp_centrality %>%
    arrange(desc(degree))
##                         mp_name degree
## peteraltmaier     peteraltmaier    263
## kahrs                     kahrs    251
## sigmargabriel     sigmargabriel    249
## katarinabarley   katarinabarley    225
## c_lindner             c_lindner    223
## hubertus_heil     hubertus_heil    221
## larsklingbeil     larsklingbeil    217
## petertauber         petertauber    193
## sven_kindler       sven_kindler    184
## berlinliebich     berlinliebich    179
## tobiaslindner     tobiaslindner    176
## schneidercar       schneidercar    163
## cem_oezdemir       cem_oezdemir    162
## soerenbartol       soerenbartol    161
## rbrinkhaus           rbrinkhaus    161
## danielakolbe       danielakolbe    155
## mvabercron           mvabercron    151
## groehe                   groehe    144
## johannesvogel     johannesvogel    144
## f_schaeffler       f_schaeffler    140
## svenlehmann         svenlehmann    140
## agnieszka_mdb     agnieszka_mdb    138
## oezoguz                 oezoguz    138
## larscastellucci larscastellucci    134
## katjakipping       katjakipping    133
## swenschulz           swenschulz    130
## nouripour             nouripour    130
## katjadoerner       katjadoerner    130
## baerbelbas           baerbelbas    130
## tj_tweets             tj_tweets    129
## nicolabeerfdp     nicolabeerfdp    126
## ekindeligoez       ekindeligoez    125
## lisapaus               lisapaus    121
## wanderwitz           wanderwitz    120
## s_schwartze         s_schwartze    118
## stadler_svenja   stadler_svenja    116
## jimmyschulz         jimmyschulz    115
## stephankuehn       stephankuehn    113
## stonie_kiel         stonie_kiel    111
## ulle_schauws       ulle_schauws    110
## anked                     anked    109
## juergenhardt       juergenhardt    109
## sebast_hartmann sebast_hartmann    109
## julia_verlinden julia_verlinden    106
## monikalazar         monikalazar    104
## katdro                   katdro    103
## fbrantner             fbrantner    103
## marcobuelow         marcobuelow    100
## meister_schafft meister_schafft     98
## franksitta           franksitta     97
## c_jung77               c_jung77     97
## rischwasu             rischwasu     96
## voglerk                 voglerk     94
## annachristmann   annachristmann     94
## helgelindh           helgelindh     94
## markuskurthmdb   markuskurthmdb     93
## edrossmann           edrossmann     92
## mischrodi             mischrodi     92
## crueffer               crueffer     91
## b_riexinger         b_riexinger     91
## arnoklare             arnoklare     90
## ebner_sha             ebner_sha     90
## jankortemdb         jankortemdb     89
## smuellermdb         smuellermdb     89
## matschie               matschie     89
## michaelgrossmdb michaelgrossmdb     88
## hahnflo                 hahnflo     87
## matthiasbartke   matthiasbartke     86
## badulrichmartha badulrichmartha     86
## michael_thews     michael_thews     84
## dieschmidt           dieschmidt     83
## koehler_fdp         koehler_fdp     81
## kaiwegner             kaiwegner     80
## filizgreen           filizgreen     80
## thomasgebhart     thomasgebhart     79
## starkwatzinger   starkwatzinger     78
## tpflueger             tpflueger     78
## christianduerr   christianduerr     74
## dorobaer               dorobaer     72
## bstrasser             bstrasser     71
## joloulou               joloulou     71
## stamm_fibich       stamm_fibich     70
## fritzfelgentreu fritzfelgentreu     69
## pascalmeiser       pascalmeiser     68
## th_sattelberger th_sattelberger     68
## florianpronold   florianpronold     67
## kerstingriese     kerstingriese     67
## solms                     solms     67
## ullinissen           ullinissen     66
## ruppert_stefan   ruppert_stefan     66
## victorperli         victorperli     66
## lgbeutin               lgbeutin     66
## ernst_klaus         ernst_klaus     65
## dittmarsabine     dittmarsabine     65
## w_sk                       w_sk     62
## josip_juratovic josip_juratovic     61
## torstenherbst     torstenherbst     60
## hacker_fdp           hacker_fdp     60
## busen_mdb             busen_mdb     60
## heikomaas             heikomaas     60
## fjunge                   fjunge     59
## ch_buchholz         ch_buchholz     57
## frankeedgar         frankeedgar     57
## muellerboehm       muellerboehm     57
## anjaweisgerber   anjaweisgerber     55
## evahoegl               evahoegl     55
## chriskuehn_mdb   chriskuehn_mdb     53
## brihasselmann     brihasselmann     53
## soenkerix             soenkerix     51
## matthiaszimmer   matthiaszimmer     50
## johann_saathoff johann_saathoff     47
## metinhakverdi     metinhakverdi     47
## mrosek1958           mrosek1958     47
## uwe_kamann           uwe_kamann     47
## frankschwabe       frankschwabe     46
## ulschzi                 ulschzi     46
## konstantinnotz   konstantinnotz     45
## dr_tiemann           dr_tiemann     45
## katrin_staffler katrin_staffler     45
## thomashitschler thomashitschler     44
## martinrosemann   martinrosemann     44
## karambadiaby       karambadiaby     44
## kerstinandreae   kerstinandreae     44
## derdanyal             derdanyal     44
## betmueller           betmueller     43
## katjamast             katjamast     43
## stefankaufmann   stefankaufmann     42
## mastrackzi           mastrackzi     42
## tabearoessner     tabearoessner     41
## h_weyel                 h_weyel     41
## k_sa                       k_sa     40
## kaigehring           kaigehring     40
## muellerchemnitz muellerchemnitz     40
## fdp_hessel           fdp_hessel     40
## timon_gremmels   timon_gremmels     40
## manjaschuele       manjaschuele     40
## lenibreymaier     lenibreymaier     40
## cpetrymdb             cpetrymdb     39
## goeringeckardt   goeringeckardt     38
## langemdb               langemdb     38
## uligroetsch         uligroetsch     38
## lothar_binding   lothar_binding     38
## abaerbock             abaerbock     38
## korkmazgt             korkmazgt     38
## carstentraeger   carstentraeger     37
## pschnieder           pschnieder     37
## miro_spd               miro_spd     36
## burkertmartin     burkertmartin     36
## nielsannen           nielsannen     36
## jowadephul           jowadephul     35
## achim_p                 achim_p     35
## jbrandenburgfdp jbrandenburgfdp     35
## axelgehrke           axelgehrke     35
## c_bernstiel         c_bernstiel     35
## brafdp                   brafdp     35
## nadineschoen       nadineschoen     34
## gruenebeate         gruenebeate     34
## stephanthomae     stephanthomae     34
## manuelhoeferlin manuelhoeferlin     34
## frank_pasemann   frank_pasemann     34
## ttte94                   ttte94     34
## ronjakemmer         ronjakemmer     33
## marcusfaber         marcusfaber     33
## mtodtenhausen     mtodtenhausen     32
## kleikert               kleikert     32
## olliluksic           olliluksic     32
## danielakluckert danielakluckert     32
## petra_sitte_mdb petra_sitte_mdb     31
## kaczmarekoliver kaczmarekoliver     31
## conni_moehring   conni_moehring     31
## canselk                 canselk     31
## birke_bull           birke_bull     31
## konstantinkuhle konstantinkuhle     30
## steinekecdu         steinekecdu     30
## oliver_krischer oliver_krischer     30
## nikolasloebel     nikolasloebel     30
## marcusweinberg   marcusweinberg     29
## volkerullrich     volkerullrich     29
## toens_nrw04         toens_nrw04     29
## paulziemiak         paulziemiak     29
## hildemattheis     hildemattheis     28
## gero_storjohann gero_storjohann     28
## lischkab               lischkab     28
## ruedigerkruse     ruedigerkruse     28
## owvonholtz           owvonholtz     28
## mbiadaczmdb         mbiadaczmdb     28
## jtrittin               jtrittin     27
## marcobuschmann   marcobuschmann     27
## brunnerganzohr   brunnerganzohr     26
## florianpost         florianpost     26
## steffilemke         steffilemke     26
## uwekekeritz         uwekekeritz     26
## hajdukbundestag hajdukbundestag     26
## steffenbilger     steffenbilger     26
## gruenclaudia       gruenclaudia     26
## kemmerichthl       kemmerichthl     25
## babetteschefin   babetteschefin     25
## renatekuenast     renatekuenast     25
## mariaklschmeink mariaklschmeink     25
## djanecek               djanecek     25
## afdprotschka       afdprotschka     25
## margaretebause   margaretebause     25
## loetzschmdb         loetzschmdb     24
## thlutze                 thlutze     24
## schickgerhard     schickgerhard     24
## drandreasnick     drandreasnick     24
## karstenmoering   karstenmoering     24
## carenlay               carenlay     24
## ritahaglkehl       ritahaglkehl     24
## eskensaskia         eskensaskia     24
## mgrossebroemer   mgrossebroemer     24
## dfoest                   dfoest     24
## gtzfrmming           gtzfrmming     24
## lieblingxhain     lieblingxhain     23
## hartmutebbing     hartmutebbing     23
## espendillerm       espendillerm     23
## kirstenkappert   kirstenkappert     22
## josteiniger         josteiniger     22
## michaelleutert   michaelleutert     22
## juttakrellmann   juttakrellmann     22
## andrejhunko         andrejhunko     22
## mechthildheil     mechthildheil     22
## heikebrehmermdb heikebrehmermdb     22
## otto_fricke         otto_fricke     22
## andi_wagner         andi_wagner     22
## leif_erik_holm   leif_erik_holm     22
## katrin_werner     katrin_werner     22
## markustressel     markustressel     21
## ulrichkelber       ulrichkelber     21
## matthiashauer     matthiashauer     21
## nicolegohlke       nicolegohlke     21
## deridder_mdb       deridder_mdb     21
## stefangelbhaar   stefangelbhaar     21
## danywagner_da     danywagner_da     21
## christophfdp       christophfdp     21
## beatewaro             beatewaro     20
## sylviapantel       sylviapantel     20
## hhirte                   hhirte     20
## sybillebenning   sybillebenning     20
## nilsschmid           nilsschmid     20
## renataalt_mdb     renataalt_mdb     20
## witt_uwe               witt_uwe     20
## zdebelhubertus   zdebelhubertus     19
## anjakarliczek     anjakarliczek     19
## marcusheld_spd   marcusheld_spd     19
## matthiasgastel   matthiasgastel     19
## hpfriedrichcsu   hpfriedrichcsu     19
## ingrid_remmers   ingrid_remmers     19
## katrinhelling     katrinhelling     19
## andreassteier     andreassteier     19
## ullmannmdb           ullmannmdb     19
## stbrandner           stbrandner     18
## uweschummer         uweschummer     18
## mwbirkwald           mwbirkwald     18
## utevogt                 utevogt     18
## niemamovassat     niemamovassat     18
## markhauptmann     markhauptmann     18
## josefoster           josefoster     18
## jenszimmermann1 jenszimmermann1     17
## diether_dehm       diether_dehm     17
## drlaunert             drlaunert     17
## peter_stein_cdu peter_stein_cdu     17
## manuelsarrazin   manuelsarrazin     17
## jenskoeppen         jenskoeppen     17
## gydej                     gydej     17
## norbert_mdb         norbert_mdb     16
## katjasuding         katjasuding     16
## martinarenner     martinarenner     16
## nordmdb                 nordmdb     16
## dietmarbartsch   dietmarbartsch     16
## linkepelli           linkepelli     16
## yvonnemagwas       yvonnemagwas     15
## susannruethrich susannruethrich     15
## florian_ossner   florian_ossner     15
## sabineleidig       sabineleidig     15
## hbraun                   hbraun     15
## jensmaierafd       jensmaierafd     15
## s_muenzenmaier   s_muenzenmaier     15
## sbarrientosk       sbarrientosk     15
## houbenreinhard   houbenreinhard     15
## fabiodemasi         fabiodemasi     14
## beatrix_vstorch beatrix_vstorch     14
## mdb_ulrike_bahr mdb_ulrike_bahr     14
## thomasoppermann thomasoppermann     14
## jm_luczak             jm_luczak     14
## matthiasheider   matthiasheider     14
## maikbeermann       maikbeermann     14
## awidmannmauz       awidmannmauz     14
## stephpilsinger   stephpilsinger     14
## zaklinnastic       zaklinnastic     13
## christianhirte   christianhirte     13
## gabiweberspd       gabiweberspd     13
## kirstentackmann kirstentackmann     13
## erwin_rueddel     erwin_rueddel     13
## dennisrohde         dennisrohde     13
## a_gloeckner         a_gloeckner     13
## m_reichardt_afd m_reichardt_afd     13
## mdbwendt               mdbwendt     12
## martin_hess_afd martin_hess_afd     12
## ingmar_jung         ingmar_jung     12
## g_ullrichfdp       g_ullrichfdp     12
## petrbystronafd   petrbystronafd     11
## andrealindholz   andrealindholz     11
## stefanrouenhoff stefanrouenhoff     11
## joanacotar           joanacotar     11
## heikehaensel       heikehaensel     10
## wellenreuther     wellenreuther     10
## andischeuer         andischeuer     10
## tschipanski         tschipanski     10
## karl_lauterbach karl_lauterbach     10
## peterheidtfdp     peterheidtfdp     10
## schwarz_spd         schwarz_spd      9
## gabihillerohm     gabihillerohm      9
## lindateuteberg   lindateuteberg      9
## mdb_lucassen       mdb_lucassen      9
## volkmarklein       volkmarklein      8
## udoschiefner       udoschiefner      8
## petrapaumahe       petrapaumahe      8
## ullajelpke           ullajelpke      7
## alexandersneu     alexandersneu      7
## dr_roy_kuehne     dr_roy_kuehne      7
## baerbelkofler     baerbelkofler      7
## hansjoerg_durz   hansjoerg_durz      7
## th_seitz_afd       th_seitz_afd      7
## renner_afd           renner_afd      7
## m_harderkuehnel m_harderkuehnel      7
## stefankeuterafd stefankeuterafd      7
## martinschulz       martinschulz      6
## steffenkotre       steffenkotre      6
## swagenknecht       swagenknecht      6
## janaschimke         janaschimke      6
## manderlagisela   manderlagisela      6
## alice_weidel       alice_weidel      6
## tobiasmpeterka   tobiasmpeterka      6
## enricokomning     enricokomning      6
## r_hartwig_afd     r_hartwig_afd      6
## udohemmelgarn     udohemmelgarn      6
## dirkspaniel         dirkspaniel      6
## elsnervongronow elsnervongronow      6
## corinnamiazga     corinnamiazga      6
## drfriesenmdb       drfriesenmdb      6
## haraldweinberg   haraldweinberg      5
## sevimdagdelen     sevimdagdelen      5
## marcbernhardafd marcbernhardafd      5
## schneider_afd     schneider_afd      5
## jochen_haug         jochen_haug      5
## chrwirthmdb         chrwirthmdb      5
## kaygottschalk1   kaygottschalk1      4
## janmetzler           janmetzler      4
## gustavherzogmdb gustavherzogmdb      4
## profmaier             profmaier      4
## hermiworld           hermiworld      3
## steffensonja       steffensonja      3
## michaelfrieser   michaelfrieser      3
## amattfeldt           amattfeldt      2
## marc_jongen         marc_jongen      2
## gottfriedcurio   gottfriedcurio      2
## tino_chrupalla   tino_chrupalla      2
## andreasbleckmdb andreasbleckmdb      2
## alexanderradwan alexanderradwan      1
## nkleinwaechter   nkleinwaechter      1

We can now create an overview for all the centrality measures we covered in the lecture:

mp_centrality %>%
  mutate('betweenness' = betweenness(mpg)) %>%
  mutate('closeness' = 1/closeness(mpg)) %>%
  arrange(desc(degree), desc(closeness))
##                         mp_name degree  betweenness closeness
## peteraltmaier     peteraltmaier    263 9.380659e+02       208
## kahrs                     kahrs    251 3.464696e+03       134
## sigmargabriel     sigmargabriel    249 1.209825e+03       198
## katarinabarley   katarinabarley    225 1.139662e+03       177
## c_lindner             c_lindner    223 1.507178e+03       194
## hubertus_heil     hubertus_heil    221 1.290571e+03       186
## larsklingbeil     larsklingbeil    217 1.101723e+03       186
## petertauber         petertauber    193 6.444855e+02       209
## sven_kindler       sven_kindler    184 9.598954e+02       171
## berlinliebich     berlinliebich    179 2.484378e+03       178
## tobiaslindner     tobiaslindner    176 1.273579e+03       153
## schneidercar       schneidercar    163 3.486469e+02       203
## cem_oezdemir       cem_oezdemir    162 3.834382e+02       212
## rbrinkhaus           rbrinkhaus    161 9.463878e+02       205
## soerenbartol       soerenbartol    161 4.743687e+02       173
## danielakolbe       danielakolbe    155 6.995823e+02       181
## mvabercron           mvabercron    151 2.503480e+03       113
## groehe                   groehe    144 2.053400e+02       231
## johannesvogel     johannesvogel    144 6.265658e+02       180
## svenlehmann         svenlehmann    140 4.824111e+02       177
## f_schaeffler       f_schaeffler    140 1.616162e+03       161
## oezoguz                 oezoguz    138 1.933255e+02       208
## agnieszka_mdb     agnieszka_mdb    138 3.721439e+02       188
## larscastellucci larscastellucci    134 2.923465e+02       188
## katjakipping       katjakipping    133 3.143866e+02       227
## nouripour             nouripour    130 2.126834e+02       215
## katjadoerner       katjadoerner    130 1.293205e+02       214
## swenschulz           swenschulz    130 1.985505e+02       196
## baerbelbas           baerbelbas    130 2.011917e+02       194
## tj_tweets             tj_tweets    129 3.170992e+02       213
## nicolabeerfdp     nicolabeerfdp    126 3.903657e+02       196
## ekindeligoez       ekindeligoez    125 2.551719e+02       192
## lisapaus               lisapaus    121 2.064836e+02       190
## wanderwitz           wanderwitz    120 5.437011e+02       198
## s_schwartze         s_schwartze    118 2.729721e+02       189
## stadler_svenja   stadler_svenja    116 1.874078e+02       188
## jimmyschulz         jimmyschulz    115 6.854173e+02       196
## stephankuehn       stephankuehn    113 2.919571e+02       193
## stonie_kiel         stonie_kiel    111 4.482941e+02       172
## ulle_schauws       ulle_schauws    110 1.350990e+02       200
## sebast_hartmann sebast_hartmann    109 9.399597e+01       212
## anked                     anked    109 2.621235e+02       207
## juergenhardt       juergenhardt    109 2.337261e+02       206
## julia_verlinden julia_verlinden    106 2.203119e+02       193
## monikalazar         monikalazar    104 1.123566e+02       207
## fbrantner             fbrantner    103 9.172660e+01       215
## katdro                   katdro    103 1.318205e+02       201
## marcobuelow         marcobuelow    100 8.618820e+01       252
## meister_schafft meister_schafft     98 1.913175e+02       212
## franksitta           franksitta     97 7.744529e+02       188
## c_jung77               c_jung77     97 2.434553e+02       180
## rischwasu             rischwasu     96 2.787949e+01       225
## annachristmann   annachristmann     94 9.568834e+01       208
## helgelindh           helgelindh     94 6.573411e+01       203
## voglerk                 voglerk     94 3.896053e+02       186
## markuskurthmdb   markuskurthmdb     93 6.987111e+01       216
## edrossmann           edrossmann     92 1.302471e+01       229
## mischrodi             mischrodi     92 2.649620e+01       208
## b_riexinger         b_riexinger     91 2.403583e+02       214
## crueffer               crueffer     91 7.952065e+01       203
## ebner_sha             ebner_sha     90 6.294377e+01       219
## arnoklare             arnoklare     90 2.421822e+01       207
## smuellermdb         smuellermdb     89 5.465586e+01       252
## jankortemdb         jankortemdb     89 1.289062e+02       212
## matschie               matschie     89 9.105211e+01       208
## michaelgrossmdb michaelgrossmdb     88 2.648164e+01       217
## hahnflo                 hahnflo     87 3.087581e+02       215
## matthiasbartke   matthiasbartke     86 3.388606e+01       214
## badulrichmartha badulrichmartha     86 8.446211e+01       200
## michael_thews     michael_thews     84 1.119217e+01       221
## dieschmidt           dieschmidt     83 1.012358e+01       226
## koehler_fdp         koehler_fdp     81 1.614472e+02       195
## filizgreen           filizgreen     80 3.210310e+01       217
## kaiwegner             kaiwegner     80 1.703597e+02       216
## thomasgebhart     thomasgebhart     79 2.307277e+02       200
## starkwatzinger   starkwatzinger     78 6.162760e+01       208
## tpflueger             tpflueger     78 1.915543e+02       191
## christianduerr   christianduerr     74 8.215310e+01       209
## dorobaer               dorobaer     72 0.000000e+00       154
## bstrasser             bstrasser     71 7.360234e+01       213
## joloulou               joloulou     71 2.910258e+01       212
## stamm_fibich       stamm_fibich     70 1.728255e+01       208
## fritzfelgentreu fritzfelgentreu     69 1.959770e+01       225
## th_sattelberger th_sattelberger     68 8.250923e+01       216
## pascalmeiser       pascalmeiser     68 1.060831e+02       201
## solms                     solms     67 2.507632e+01       236
## kerstingriese     kerstingriese     67 0.000000e+00       163
## florianpronold   florianpronold     67 0.000000e+00       159
## ruppert_stefan   ruppert_stefan     66 2.149886e+01       231
## lgbeutin               lgbeutin     66 1.195237e+02       203
## victorperli         victorperli     66 9.093854e+01       198
## ullinissen           ullinissen     66 0.000000e+00       160
## dittmarsabine     dittmarsabine     65 1.107925e+01       231
## ernst_klaus         ernst_klaus     65 9.625707e+01       214
## w_sk                       w_sk     62 0.000000e+00       169
## josip_juratovic josip_juratovic     61 2.986518e+00       297
## torstenherbst     torstenherbst     60 4.150183e+01       221
## hacker_fdp           hacker_fdp     60 2.350657e+01       215
## busen_mdb             busen_mdb     60 4.739716e+01       202
## heikomaas             heikomaas     60 0.000000e+00       170
## fjunge                   fjunge     59 1.859299e+01       232
## ch_buchholz         ch_buchholz     57 1.640907e+01       278
## muellerboehm       muellerboehm     57 2.928327e+01       206
## frankeedgar         frankeedgar     57 0.000000e+00       172
## anjaweisgerber   anjaweisgerber     55 2.727612e+01       253
## evahoegl               evahoegl     55 0.000000e+00       175
## chriskuehn_mdb   chriskuehn_mdb     53 0.000000e+00       177
## brihasselmann     brihasselmann     53 0.000000e+00       177
## soenkerix             soenkerix     51 0.000000e+00       180
## matthiaszimmer   matthiaszimmer     50 1.648965e+01       241
## mrosek1958           mrosek1958     47 3.946808e+02       290
## uwe_kamann           uwe_kamann     47 1.060285e+03       229
## metinhakverdi     metinhakverdi     47 0.000000e+00       184
## johann_saathoff johann_saathoff     47 0.000000e+00       179
## ulschzi                 ulschzi     46 7.828043e+02       247
## frankschwabe       frankschwabe     46 0.000000e+00       185
## katrin_staffler katrin_staffler     45 9.238560e+00       279
## dr_tiemann           dr_tiemann     45 6.403572e+01       200
## konstantinnotz   konstantinnotz     45 0.000000e+00       185
## martinrosemann   martinrosemann     44 0.000000e+00       189
## derdanyal             derdanyal     44 0.000000e+00       188
## thomashitschler thomashitschler     44 0.000000e+00       187
## karambadiaby       karambadiaby     44 0.000000e+00       187
## kerstinandreae   kerstinandreae     44 0.000000e+00       182
## betmueller           betmueller     43 0.000000e+00       189
## katjamast             katjamast     43 0.000000e+00       188
## mastrackzi           mastrackzi     42 0.000000e+00       189
## stefankaufmann   stefankaufmann     42 0.000000e+00       187
## tabearoessner     tabearoessner     41 0.000000e+00       190
## h_weyel                 h_weyel     41 0.000000e+00       NaN
## fdp_hessel           fdp_hessel     40 2.769231e-01       259
## timon_gremmels   timon_gremmels     40 0.000000e+00       195
## kaigehring           kaigehring     40 0.000000e+00       192
## muellerchemnitz muellerchemnitz     40 0.000000e+00       192
## manjaschuele       manjaschuele     40 0.000000e+00       192
## lenibreymaier     lenibreymaier     40 0.000000e+00       192
## k_sa                       k_sa     40 0.000000e+00       189
## cpetrymdb             cpetrymdb     39 0.000000e+00       194
## langemdb               langemdb     38 0.000000e+00       197
## korkmazgt             korkmazgt     38 0.000000e+00       197
## goeringeckardt   goeringeckardt     38 0.000000e+00       195
## abaerbock             abaerbock     38 0.000000e+00       194
## uligroetsch         uligroetsch     38 0.000000e+00       193
## lothar_binding   lothar_binding     38 0.000000e+00       193
## carstentraeger   carstentraeger     37 0.000000e+00       194
## pschnieder           pschnieder     37 0.000000e+00       189
## burkertmartin     burkertmartin     36 0.000000e+00       202
## miro_spd               miro_spd     36 0.000000e+00       195
## nielsannen           nielsannen     36 0.000000e+00       195
## axelgehrke           axelgehrke     35 2.666667e+00       397
## c_bernstiel         c_bernstiel     35 7.549374e+00       273
## achim_p                 achim_p     35 0.000000e+00       197
## jowadephul           jowadephul     35 0.000000e+00       196
## brafdp                   brafdp     35 0.000000e+00       195
## jbrandenburgfdp jbrandenburgfdp     35 0.000000e+00       192
## nadineschoen       nadineschoen     34 0.000000e+00       198
## gruenebeate         gruenebeate     34 0.000000e+00       198
## stephanthomae     stephanthomae     34 0.000000e+00       196
## manuelhoeferlin manuelhoeferlin     34 0.000000e+00       196
## frank_pasemann   frank_pasemann     34 0.000000e+00       196
## ttte94                   ttte94     34 0.000000e+00       NaN
## marcusfaber         marcusfaber     33 0.000000e+00       198
## ronjakemmer         ronjakemmer     33 0.000000e+00       193
## olliluksic           olliluksic     32 0.000000e+00       202
## kleikert               kleikert     32 0.000000e+00       200
## danielakluckert danielakluckert     32 0.000000e+00       195
## mtodtenhausen     mtodtenhausen     32 0.000000e+00       194
## kaczmarekoliver kaczmarekoliver     31 0.000000e+00       210
## birke_bull           birke_bull     31 0.000000e+00       202
## conni_moehring   conni_moehring     31 0.000000e+00       201
## petra_sitte_mdb petra_sitte_mdb     31 0.000000e+00       200
## canselk                 canselk     31 0.000000e+00       200
## oliver_krischer oliver_krischer     30 0.000000e+00       207
## steinekecdu         steinekecdu     30 0.000000e+00       202
## konstantinkuhle konstantinkuhle     30 0.000000e+00       200
## nikolasloebel     nikolasloebel     30 0.000000e+00       196
## toens_nrw04         toens_nrw04     29 0.000000e+00       209
## marcusweinberg   marcusweinberg     29 0.000000e+00       202
## volkerullrich     volkerullrich     29 0.000000e+00       197
## paulziemiak         paulziemiak     29 0.000000e+00       197
## lischkab               lischkab     28 0.000000e+00       209
## mbiadaczmdb         mbiadaczmdb     28 0.000000e+00       209
## owvonholtz           owvonholtz     28 0.000000e+00       206
## ruedigerkruse     ruedigerkruse     28 0.000000e+00       205
## hildemattheis     hildemattheis     28 0.000000e+00       203
## gero_storjohann gero_storjohann     28 0.000000e+00       NaN
## marcobuschmann   marcobuschmann     27 0.000000e+00       214
## jtrittin               jtrittin     27 0.000000e+00       205
## florianpost         florianpost     26 0.000000e+00       215
## uwekekeritz         uwekekeritz     26 0.000000e+00       212
## steffilemke         steffilemke     26 0.000000e+00       210
## brunnerganzohr   brunnerganzohr     26 0.000000e+00       208
## hajdukbundestag hajdukbundestag     26 0.000000e+00       208
## gruenclaudia       gruenclaudia     26 0.000000e+00       207
## steffenbilger     steffenbilger     26 0.000000e+00       200
## babetteschefin   babetteschefin     25 0.000000e+00       220
## kemmerichthl       kemmerichthl     25 0.000000e+00       217
## djanecek               djanecek     25 0.000000e+00       212
## renatekuenast     renatekuenast     25 0.000000e+00       208
## margaretebause   margaretebause     25 0.000000e+00       208
## mariaklschmeink mariaklschmeink     25 0.000000e+00       207
## afdprotschka       afdprotschka     25 0.000000e+00       202
## schickgerhard     schickgerhard     24 0.000000e+00       221
## ritahaglkehl       ritahaglkehl     24 0.000000e+00       217
## karstenmoering   karstenmoering     24 0.000000e+00       211
## eskensaskia         eskensaskia     24 0.000000e+00       211
## dfoest                   dfoest     24 0.000000e+00       211
## loetzschmdb         loetzschmdb     24 0.000000e+00       208
## carenlay               carenlay     24 0.000000e+00       208
## mgrossebroemer   mgrossebroemer     24 0.000000e+00       208
## gtzfrmming           gtzfrmming     24 0.000000e+00       204
## drandreasnick     drandreasnick     24 0.000000e+00       202
## thlutze                 thlutze     24 0.000000e+00       NaN
## lieblingxhain     lieblingxhain     23 0.000000e+00       210
## hartmutebbing     hartmutebbing     23 0.000000e+00       210
## espendillerm       espendillerm     23 0.000000e+00       206
## kirstenkappert   kirstenkappert     22 0.000000e+00       228
## josteiniger         josteiniger     22 0.000000e+00       215
## mechthildheil     mechthildheil     22 0.000000e+00       214
## katrin_werner     katrin_werner     22 0.000000e+00       214
## juttakrellmann   juttakrellmann     22 0.000000e+00       213
## otto_fricke         otto_fricke     22 0.000000e+00       212
## michaelleutert   michaelleutert     22 0.000000e+00       210
## andrejhunko         andrejhunko     22 0.000000e+00       210
## andi_wagner         andi_wagner     22 0.000000e+00       210
## leif_erik_holm   leif_erik_holm     22 0.000000e+00       206
## heikebrehmermdb heikebrehmermdb     22 0.000000e+00       204
## markustressel     markustressel     21 0.000000e+00       227
## deridder_mdb       deridder_mdb     21 0.000000e+00       222
## ulrichkelber       ulrichkelber     21 0.000000e+00       217
## christophfdp       christophfdp     21 0.000000e+00       217
## matthiashauer     matthiashauer     21 0.000000e+00       216
## danywagner_da     danywagner_da     21 0.000000e+00       214
## nicolegohlke       nicolegohlke     21 0.000000e+00       212
## stefangelbhaar   stefangelbhaar     21 0.000000e+00       211
## renataalt_mdb     renataalt_mdb     20 0.000000e+00       223
## sylviapantel       sylviapantel     20 0.000000e+00       219
## nilsschmid           nilsschmid     20 0.000000e+00       219
## beatewaro             beatewaro     20 0.000000e+00       215
## witt_uwe               witt_uwe     20 0.000000e+00       208
## sybillebenning   sybillebenning     20 0.000000e+00       207
## hhirte                   hhirte     20 0.000000e+00       206
## matthiasgastel   matthiasgastel     19 0.000000e+00       234
## katrinhelling     katrinhelling     19 0.000000e+00       228
## hpfriedrichcsu   hpfriedrichcsu     19 0.000000e+00       227
## anjakarliczek     anjakarliczek     19 0.000000e+00       223
## marcusheld_spd   marcusheld_spd     19 0.000000e+00       223
## ullmannmdb           ullmannmdb     19 0.000000e+00       221
## ingrid_remmers   ingrid_remmers     19 0.000000e+00       216
## zdebelhubertus   zdebelhubertus     19 0.000000e+00       214
## andreassteier     andreassteier     19 0.000000e+00       207
## josefoster           josefoster     18 1.743605e+00       297
## utevogt                 utevogt     18 0.000000e+00       242
## markhauptmann     markhauptmann     18 0.000000e+00       232
## mwbirkwald           mwbirkwald     18 0.000000e+00       219
## niemamovassat     niemamovassat     18 0.000000e+00       215
## stbrandner           stbrandner     18 0.000000e+00       211
## uweschummer         uweschummer     18 0.000000e+00       208
## drlaunert             drlaunert     17 0.000000e+00       234
## jenskoeppen         jenskoeppen     17 0.000000e+00       231
## gydej                     gydej     17 0.000000e+00       230
## jenszimmermann1 jenszimmermann1     17 0.000000e+00       219
## diether_dehm       diether_dehm     17 0.000000e+00       216
## manuelsarrazin   manuelsarrazin     17 0.000000e+00       215
## peter_stein_cdu peter_stein_cdu     17 0.000000e+00       210
## linkepelli           linkepelli     16 0.000000e+00       227
## norbert_mdb         norbert_mdb     16 0.000000e+00       223
## katjasuding         katjasuding     16 0.000000e+00       221
## martinarenner     martinarenner     16 0.000000e+00       220
## nordmdb                 nordmdb     16 0.000000e+00       216
## dietmarbartsch   dietmarbartsch     16 0.000000e+00       216
## yvonnemagwas       yvonnemagwas     15 0.000000e+00       250
## s_muenzenmaier   s_muenzenmaier     15 0.000000e+00       230
## susannruethrich susannruethrich     15 0.000000e+00       229
## houbenreinhard   houbenreinhard     15 0.000000e+00       229
## hbraun                   hbraun     15 0.000000e+00       227
## sbarrientosk       sbarrientosk     15 0.000000e+00       227
## sabineleidig       sabineleidig     15 0.000000e+00       224
## jensmaierafd       jensmaierafd     15 0.000000e+00       219
## florian_ossner   florian_ossner     15 0.000000e+00       211
## mdb_ulrike_bahr mdb_ulrike_bahr     14 0.000000e+00       256
## maikbeermann       maikbeermann     14 0.000000e+00       235
## thomasoppermann thomasoppermann     14 0.000000e+00       232
## beatrix_vstorch beatrix_vstorch     14 0.000000e+00       229
## jm_luczak             jm_luczak     14 0.000000e+00       226
## awidmannmauz       awidmannmauz     14 0.000000e+00       223
## fabiodemasi         fabiodemasi     14 0.000000e+00       221
## matthiasheider   matthiasheider     14 0.000000e+00       221
## stephpilsinger   stephpilsinger     14 0.000000e+00       212
## erwin_rueddel     erwin_rueddel     13 0.000000e+00       257
## kirstentackmann kirstentackmann     13 0.000000e+00       235
## a_gloeckner         a_gloeckner     13 0.000000e+00       231
## zaklinnastic       zaklinnastic     13 0.000000e+00       230
## m_reichardt_afd m_reichardt_afd     13 0.000000e+00       229
## gabiweberspd       gabiweberspd     13 0.000000e+00       226
## christianhirte   christianhirte     13 0.000000e+00       225
## dennisrohde         dennisrohde     13 0.000000e+00       224
## mdbwendt               mdbwendt     12 0.000000e+00       251
## g_ullrichfdp       g_ullrichfdp     12 0.000000e+00       238
## martin_hess_afd martin_hess_afd     12 0.000000e+00       234
## ingmar_jung         ingmar_jung     12 0.000000e+00       214
## joanacotar           joanacotar     11 0.000000e+00       235
## petrbystronafd   petrbystronafd     11 0.000000e+00       234
## andrealindholz   andrealindholz     11 0.000000e+00       216
## stefanrouenhoff stefanrouenhoff     11 0.000000e+00       216
## wellenreuther     wellenreuther     10 0.000000e+00       274
## tschipanski         tschipanski     10 0.000000e+00       255
## andischeuer         andischeuer     10 0.000000e+00       253
## peterheidtfdp     peterheidtfdp     10 0.000000e+00       244
## heikehaensel       heikehaensel     10 0.000000e+00       243
## karl_lauterbach karl_lauterbach     10 0.000000e+00       241
## schwarz_spd         schwarz_spd      9 5.877617e-02       296
## lindateuteberg   lindateuteberg      9 0.000000e+00       241
## gabihillerohm     gabihillerohm      9 0.000000e+00       234
## mdb_lucassen       mdb_lucassen      9 0.000000e+00       217
## volkmarklein       volkmarklein      8 0.000000e+00       284
## udoschiefner       udoschiefner      8 0.000000e+00       236
## petrapaumahe       petrapaumahe      8 0.000000e+00       224
## m_harderkuehnel m_harderkuehnel      7 0.000000e+00       301
## th_seitz_afd       th_seitz_afd      7 0.000000e+00       288
## dr_roy_kuehne     dr_roy_kuehne      7 0.000000e+00       273
## baerbelkofler     baerbelkofler      7 0.000000e+00       268
## ullajelpke           ullajelpke      7 0.000000e+00       243
## alexandersneu     alexandersneu      7 0.000000e+00       229
## hansjoerg_durz   hansjoerg_durz      7 0.000000e+00       220
## renner_afd           renner_afd      7 0.000000e+00       220
## stefankeuterafd stefankeuterafd      7 0.000000e+00       220
## steffenkotre       steffenkotre      6 0.000000e+00       331
## alice_weidel       alice_weidel      6 0.000000e+00       331
## tobiasmpeterka   tobiasmpeterka      6 0.000000e+00       331
## enricokomning     enricokomning      6 0.000000e+00       331
## r_hartwig_afd     r_hartwig_afd      6 0.000000e+00       331
## udohemmelgarn     udohemmelgarn      6 0.000000e+00       331
## dirkspaniel         dirkspaniel      6 0.000000e+00       331
## elsnervongronow elsnervongronow      6 0.000000e+00       331
## janaschimke         janaschimke      6 0.000000e+00       286
## drfriesenmdb       drfriesenmdb      6 0.000000e+00       275
## manderlagisela   manderlagisela      6 0.000000e+00       274
## swagenknecht       swagenknecht      6 0.000000e+00       256
## martinschulz       martinschulz      6 0.000000e+00       240
## corinnamiazga     corinnamiazga      6 0.000000e+00       221
## chrwirthmdb         chrwirthmdb      5 0.000000e+00       346
## marcbernhardafd marcbernhardafd      5 0.000000e+00       332
## schneider_afd     schneider_afd      5 0.000000e+00       332
## jochen_haug         jochen_haug      5 0.000000e+00       306
## haraldweinberg   haraldweinberg      5 0.000000e+00       291
## sevimdagdelen     sevimdagdelen      5 0.000000e+00       244
## kaygottschalk1   kaygottschalk1      4 0.000000e+00       333
## janmetzler           janmetzler      4 0.000000e+00       304
## profmaier             profmaier      4 0.000000e+00       300
## gustavherzogmdb gustavherzogmdb      4 0.000000e+00       242
## michaelfrieser   michaelfrieser      3 0.000000e+00       320
## steffensonja       steffensonja      3 0.000000e+00       293
## hermiworld           hermiworld      3 0.000000e+00       NaN
## gottfriedcurio   gottfriedcurio      2 0.000000e+00       402
## marc_jongen         marc_jongen      2 0.000000e+00       350
## andreasbleckmdb andreasbleckmdb      2 0.000000e+00       350
## tino_chrupalla   tino_chrupalla      2 0.000000e+00       341
## amattfeldt           amattfeldt      2 0.000000e+00       313
## alexanderradwan alexanderradwan      1 0.000000e+00       328
## nkleinwaechter   nkleinwaechter      1 0.000000e+00         1

You can see from the table that different centrality measures produce different rankings of importance in the network.

To better distinguish the parties on our network plot, we’ll define some colors.

party_colors <- c(
     'SPD' = '#CC0000',
     'CDU' = '#000000',
     'DIE GRÜNEN' = '#33D633',
     'DIE LINKE' = '#800080',
     'FDP' = '#EEEE00',
     'AfD' = '#0000ED',
     'CSU' = '#ADD8E6'
)
# add transparency as hex code (25% transparency)
party_colors_semitransp <- paste0(party_colors, '25')   
names(party_colors_semitransp) <- names(party_colors)

# assign the colors to nodes and edges based on party
V(mpg)$color <- party_colors[V(mpg)$party]
E(mpg)$color <- party_colors_semitransp[E(mpg)$from_party]

Now, let’s try to take another look at the data. Because of the size of the data, we will need to rely on a layout algorithm provided in igraph.

mpg_layout <- layout_with_drl(mpg, options=list(simmer.attraction=0))

Now, we can pass this to the plot function.

plot(mpg, layout = mpg_layout)

plot(mpg, layout = mpg_layout,
      vertex.size = 2,
      vertex.label = NA,
      vertex.label.dist = 0.5, vertex.frame.color = NA,
      edge.arrow.size = 0.2, edge.curved = TRUE)
      title('Twitter network of members of the German Bundestag',
      cex = 1.2, line = -0.5)
      
      # add a legend
      legend('topright', legend = names(party_colors), col = party_colors,
       pch = 15, bty = "n",  pt.cex = 1.25, cex = 0.8,
       text.col = "black", horiz = FALSE)

We can also look at the connections of members of specific parties only by subsetting the network like this:

# this graphs shows all follows of CDU mps

mpg %>%
  subgraph.edges(eids=which(E(mpg)$from_party=="CDU")) %>%
  plot(
      vertex.size = 2,
      vertex.label = NA,
      vertex.label.dist = 0.5, vertex.frame.color = NA,
      edge.arrow.size = 0.2, edge.curved = TRUE)
      title('Twitter follows of CDU members of the German Bundestag',
      cex = 1.2, line = -0.5)
      # add a legend
      legend('topright', legend = names(party_colors), col = party_colors,
       pch = 15, bty = "n",  pt.cex = 1.25, cex = 0.8,
       text.col = "black", horiz = FALSE)

We can also use another interactive plotting method form the visNetwork package. You can use this code to do so6:

install.packages('visNetwork')
library(visNetwork)

vis_nw_data <- toVisNetworkData(mpg)

vis_nw_data$nodes$title <- sprintf('@%s (%s %s)', vis_nw_data$nodes$id,
                                    vis_nw_data$nodes$personal.first_name,
                                    vis_nw_data$nodes$personal.last_name)

vis_nw_data$edges$color <- substr(vis_nw_data$edges$color, 0, 7)

vis_legend_data <- data.frame(label = names(party_colors),
                              color = unname(party_colors),
                              shape = 'square')


visNetwork(nodes = vis_nw_data$nodes, edges = vis_nw_data$edges,
           height = '700px', width = '90%') %>%
     # use same layout as before
     visIgraphLayout(layout = 'layout_with_drl',
                     options=list(simmer.attraction=0)) %>%
     # and same transparency
     visEdges(color = list(opacity = 0.25), arrows = 'to') %>%
     # set node highlighting
     visNodes(labelHighlightBold = TRUE, borderWidth = 1,
              borderWidthSelected = 12) %>%
     # add legend
     visLegend(addNodes = vis_legend_data, useGroups = FALSE,
               zoom = FALSE, width = 0.2) %>%
     # show drop down menus and highlight nearest edges
     visOptions(nodesIdSelection = TRUE, highlightNearest = TRUE,
                selectedBy = 'party') %>%
     # disable dragging of nodes
     visInteraction(dragNodes = FALSE)

Using the information from this network, e.g. centrality measures, we could check whether Twitter centrality reflects, e.g. intra- / inter-party voting behavior or addressees in Bundestag speeches.

Further resources

The igraph package has a lot more functionalities than just those that we explored here. Check out Mark Hoffman’s course ‘Methods for Network Analysis’ which is also a great resource for network anaylsis in R.] and the igraph documentation for more.


  1. Note: we could also load the entire tidyverse here but since we only need some functionality, so we’ll stick to dplyr.↩︎

  2. Parts of this section are inspired by Mark Hoffman’s course ‘Methods for Network Analysis’ which is also a great resource for network anaylsis in R.↩︎

  3. Note that in igraph, just nodes are called vertices (as they usually are in graph theory).↩︎

  4. We will explore how to improve the plot graphs some more in the next section.↩︎

  5. Note: This section is based on Markus Konrad’s analysis↩︎

  6. Taken verbatim from https://datascience.blog.wzb.eu/2019/07/11/a-twitter-network-of-members-of-the-19th-german-bundestag-part-ii/. Head there for explanations↩︎